package com.superpet.weixin.api.login;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.superpet.common.kits.ConstantKit;
import com.superpet.common.kits.WeixinKit;
import com.superpet.common.model.Pets;
import com.superpet.common.vo.WxSessionVo;
import com.superpet.weixin.api.User.UserService;
import com.superpet.weixin.api.pet.PetService;
import org.apache.commons.lang3.StringUtils;

import java.math.BigInteger;
import java.util.List;

public class LoginController extends Controller {
	
	static LoginService srv = LoginService.me;

	public void index() {
		render("index.html");
	}
	/**
	 * 微信小程序登录
	 * 1、通过页面传过来的jsCode，到微信服务器获取openid和sessionKey
	 * 2、新用户入库
	 * 3、生成本服务器的token（session）
	 * 4、token入库和如缓存，以token为key，存储openid和sessionKey
	 * 5、返回token给客户端
	 */
	@Before(Tx.class)
	public void doLogin(){
		String jsCode = getPara("jsCode");
		WxSessionVo wxVo = WeixinKit.getWxSession(jsCode);
		if(!StringUtils.isNotBlank(wxVo.getErrcode())){
			Long userId = UserService.me.saveOrUpdateUser(wxVo);
			String accessToken = HashKit.generateSalt(64);
			wxVo.setAccessToken(accessToken);
			wxVo.setUserId(userId);
			srv.saveToken(wxVo);

			List<Pets> pets = PetService.me.getUserPetList(userId);
			int petsCount = 0;
			if(pets!=null && !pets.isEmpty()){
				petsCount = pets.size();
			}
			renderJson(Ret.ok("code", ConstantKit.CODE_SUCCESS).set("msg",ConstantKit.MSG_SUCCESS).set("accessToken",accessToken).set("petsCount",petsCount));
		}else{
			renderJson(Ret.fail("code",ConstantKit.CODE_WX_FAIL).set("msg",ConstantKit.MSG_SUCCESS+wxVo.getErrmsg()));
		}
	}

}
